<!-- 新建实物奖品 -->
<template>
  <a-drawer v-model:visible="vdata.visible" :maskClosable="false" width="40%">
    <template #title>
      <div style="display:flex;justify-content:space-between;align-items:center;">
        <span v-if="vdata.isAdd">新增虚拟卡券</span>
        <span v-if="!vdata.isAdd">修改虚拟卡券</span>
        <a-button :disabled="vdata.disabled" @click="handleOkFunc(true)">保存草稿</a-button>
      </div>
    </template>
    <a-form
      ref="formRef"
      :model="vdata.saveObject"
      layout="vertical"
      labelAlign="left"
      :rules="vdata.rules"
      :colon="false"
      :wrapper-col="{ span: 22 }"
      style="margin-top: 30px; margin-left: 20px"
    >
      <a-row>
        <!-- <a-col :span="24">
          <a-form-item label="账户登录机构归属关系" name="agentNo">
            <gzLink 
              :default-value="defaultCity"
              @change="handleCityChange"
            />
          </a-form-item>
        </a-col> -->
        <a-col :span="12">
          <a-form-item label="客户经理姓名" name="couponDes">
            <a-input
              v-model:value="vdata.saveObject['couponDes']"
              :disabled="vdata.disabled"
              placeholder="请输入客户经理姓名"
              :maxlength="16"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="客户经理手机号" name="couponDes">
            <a-input
              v-model:value="vdata.saveObject['couponDes']"
              :disabled="vdata.disabled"
              placeholder="请输入客户经理手机号"
              :maxlength="16"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="微信小程序唯一标识" name="couponDes">
            <a-input
              v-model:value="vdata.saveObject['couponDes']"
              :disabled="vdata.disabled"
              placeholder="请输入微信小程序唯一标识"
              :maxlength="16"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" style="margin-right: 8px" @click="onClose">
        <close-outlined />
        取消
      </a-button>
      <a-button type="primary" :loading="vdata.btnLoading" @click="handleOkFunc(false)">
        <check-outlined />
        保存
      </a-button>
    </div>
  </a-drawer>
</template>
  
  <script setup lang="ts">
  import{$virtualDetail,$virtualAdd,$virtualEdit,$getVirtualGoodsGoods}from '@/api/awardMange/virtualCoupon/index'
  import { reactive, ref, defineExpose, watch, getCurrentInstance } from 'vue'
  const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties
  const formRef = ref()
  
  const props = defineProps(['callbackFunc'])

  const defaultCity = ref({
    province: '41022445',
})

const currentSelection = ref({})

const handleCityChange = (value) => {
  currentSelection.value = value
  console.log('城市选择变化:', value)
}
  
  const vdata: any = reactive({
    isAdd: false, // 新增OR修改
    visible: false,
    btnLoading: true,
    minVirtualCouponNum: 1,
    disabled: false,
    saveObject: {
      
    },
    rules: {
      agentNo: [{ required: true, message: '机构号不能为空', trigger: 'blur' },],
      goodsNum: [{ required: true, message: '数量不能为空', trigger: 'blur' },],
      insideGoodsId: [{ required: true, message: '内部商品不能为空', trigger: 'change' },],
      // isLimitUser: [{ required: true, message: '发放客户限制不能为空', trigger: 'change' },],
      everyoneMaxNum :[{ required: true, message: '数量不能为空', trigger: 'blur' },],
  
      limitUserContent: [{ required: true, message: '等级不能为空', trigger: 'change' },],
    },
  })
  const productObj = ref({}) as any 
  const productType = ref('') as any 
  function handleChange(val) {
  // 
  productObj.value =  ruleListProduct.value.filter(item=>item.virtualInsideId == val)
  productType.value = productObj.value.type
  }
  const ruleListProduct = ref([{
    virtualInsideId: '',
    goodsName: '',
  }])
  function focus() {
    $getVirtualGoodsGoods().then(res => {
      console.log(res,'卡券信息')
      ruleListProduct.value = res
      // console.log(ruleListProduct.value);
    })
  
  
  }
  
  /**
   * 周期性中奖限制校验
   */
   function periodTimesValidator() {
    if (vdata.saveObject['periodType'] !== 0 && !vdata.saveObject['periodTimes']) {
      return Promise.reject('周期性限制不能为空')
    } else {
      return Promise.resolve()
    }
  }
  function handleOkFunc(isDraft) {
    // 提示信息
    const message = isDraft ? '保存成功' : (vdata.isAdd ? '新增成功' : '修改成功')
    // 请求方法
    const method = !vdata.isAdd ? 'PUT' : 'POST'
    let uploadObject = { ...vdata.saveObject, rule: {} }  // 初始化上传参数
    if (isDraft) {  // 保存草稿
      clearFieldValidate()  // 如果之前点击过提交，需要清除之前的验证
      formRef.value.validateFields(['virtualCouponName']).then(() => {  // 保存草稿只验证虚拟券名称
        requestFunc(method, uploadObject, message)
      }).catch(() => { })
      return
    }
  
    formRef.value.validate().then(() => {
      requestFunc(method, { ...uploadObject, state: 2 }, message)
    }).catch(() => { })
  }
  // 发起请求
  function requestFunc(method, uploadObject, message) {
    vdata.btnLoading = true
    if(vdata.isAdd){
       // 限制用户
    // 客户限制处理
    if((uploadObject.isLimitUser === 2 || uploadObject.isLimitUser === 3) && uploadObject.limitUserContent?.length){
      uploadObject.limitUserContent = uploadObject.limitUserContent.map(item => item).join(',')
    }else{
      uploadObject.limitUserContent = ''
    }
      console.log(uploadObject,'新增传入的值')
      $virtualAdd(method, uploadObject).then(() => {
  
      $infoBox.message.success(message)
      props.callbackFunc()
      onClose()
    }).finally(() => {
      vdata.btnLoading = false
    })
    }else{
        // 客户限制处理
    if((uploadObject.isLimitUser === 2 || uploadObject.isLimitUser === 3) && uploadObject.limitUserContent?.length){
      uploadObject.limitUserContent = uploadObject.limitUserContent.map(item => item).join(',')
    }else{
      uploadObject.limitUserContent = ''
    }
      $virtualEdit(method, uploadObject).then(() => {
      $infoBox.message.success(message)
      props.callbackFunc()
      onClose()
    }).finally(() => {
      vdata.btnLoading = false
    })
    }
   
  }
  
  function onClose() {
    vdata.visible = false
  }
  
  // 添加规则
  function ruleAdd() {
    vdata.ruleList.push({ k: '', v: '' })
  }
  // 删除规则
  function ruleReduce() {
    vdata.ruleList.pop()
  }
  
  function show(virtualId:any, disabled:any, virtualCouponNum:any) {
    vdata.isAdd = !virtualId
    vdata.virtualId = virtualId
    vdata.btnLoading = false
    vdata.ruleList = []
    // 重置数据
    vdata.saveObject = {
      everyonePeriodType:0,
      isLimitUser:0
    }
    vdata.minVirtualCouponNum = virtualCouponNum
    vdata.disabled = disabled
    clearFieldValidate()
    if (vdata.isAdd) { // 新增
      vdata.visible = true
    } else {  // 修改
      vdata.visible = true
      // // 限制用户
      // if(vdata.saveObject.isLimitUser === 2 || vdata.saveObject.isLimitUser === 3){
      //       vdata.saveObject.limitUserContent = vdata.saveObject.limitUserContent.split(',').map(item => +item)
      //     }else{
      //       vdata.saveObject.limitUserContent = []
      //     }
      // $virtualDetail({ virtualId }).then(res => {
      //   ruleListProduct.value = [{virtualInsideId:res.awardVirtualInsideEntity.virtualInsideId,goodsName:res.awardVirtualInsideEntity.goodsName}]
      //   vdata.saveObject = { ...res,...res.awardSetting }   
  
      //           // 限制用户
      //           if(vdata.saveObject.isLimitUser === 2 || vdata.saveObject.isLimitUser === 3){
      //       vdata.saveObject.limitUserContent = vdata.saveObject.limitUserContent.split(',').map(item => +item)
      //     }else{
      //       vdata.saveObject.limitUserContent = []
      //     }
      //   console.log(res)
      //   productType.value = res.awardVirtualInsideEntity.type
      //   vdata.visible = true
      // })
    }
  }
  // 清除字段验证
  function clearFieldValidate() {
    if (formRef.value !== undefined) {
      formRef.value.clearValidate()
    }
  }
  
  defineExpose({
    show,
  })
  </script>
  
  <style lang="less" scoped>
  .rule {
    display: flex;
    align-items: center;
    gap: 20px;
  
    * {
      flex-shrink: 0;
    }
  
    &:nth-child(n + 2) {
      margin-top: 10px;
    }
  }
  
  .cp {
    cursor: pointer;
  }
  
  .fz18 {
    font-size: 18px;
  }
  </style>
  